using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Core;
using FreeLancer.HRB.Core.Web.Controls;
using FreeLancer.HRB.Services;

namespace FreeLancer.HRB.WebApp
{
  public partial class Post : WebBasePage
  {
    protected void Page_Init(object sender, EventArgs e)
    {
      if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
      {
        CommentPane.PostId = new Guid(Request.QueryString["id"]);
      }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      //if (!IsCallback)
      {
        if (Request.RawUrl.Contains("?id=") && Request.QueryString["id"].Length == 36)
        {
          Guid id = new Guid(Request.QueryString["id"]);
          Posts postData = GlobalCache.PostServiceInstance.GetByPostId(id);

          FreeLancer.HRB.Core.Post post = null;
          if (postData != null)
            post = new FreeLancer.HRB.Core.Post(postData);

          if (post != null)
          {
            Response.Clear();
            Response.StatusCode = 301;
            Response.AppendHeader("location", post.RelativeLink.ToString());
            Response.End();
          }
          else
          {
            Response.Redirect(Utils.RelativeWebRoot + "Error404.aspx", true);
          }
        }
      }

      if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
      {
        InitializePageData();
      }
      else
      {
        Response.Redirect(Utils.RelativeWebRoot + "Error404.aspx", true);
      }
    }

    private void InitializePageData()
    {
      Guid id = new Guid(Request.QueryString["id"]);
      Posts postData = GlobalCache.PostServiceInstance.GetByPostId(id);

      CommentPane.IsCommentAllowed = (bool)postData.IsCommentAllowed;

      TList<PostCategory> postCategories = new PostCategoryService().GetByPostId(id);
      if (postCategories.Count > 0)
      {
        Categories category = GlobalCache.CategoriesService.
          GetByCategoryIdLanguageId(postCategories[0].CategoryId, _languageId);

        anchorCategoryName.HRef = "~/Category.aspx?id=" + category.CategoryId.ToString();
        anchorCategoryName.InnerText = category.CategoryName;
        anchorCategoryName.Title = category.CategoryName;

        anchorMoreNews.HRef = "~/Category.aspx?id=" + category.CategoryId.ToString();

        InitializeMoreNewsData(category.CategoryId, postData, 3);
      }

      h2Title.InnerText = postData.Title;
      spanDateTime.InnerText = postData.DateCreated.ToString();
      divContent.InnerHtml = postData.PostContent;
      
      Title = postData.Title + " - HRB";
      if (!string.IsNullOrEmpty(postData.AttachedPath))
      {
        divAttachedFile.Visible = true;
        linkAttachedFile.Text = postData.AttachedPath.Substring(postData.AttachedPath.IndexOf('_') + 1);
        linkAttachedFile.NavigateUrl =
          Utils.RelativeWebRoot + "Files/PostFiles/" + postData.AttachedPath;
      }
      else
      {
        divAttachedFile.Visible = false;
      }

      PreparePrintAnchor(postData.PostId.ToString());
    }

    private void InitializeMoreNewsData(Guid categoryId, Posts postData, int numberOfNews)
    {
      DataSet moreNewsData = GlobalCache.PostServiceInstance.
        GetRelatedPost(categoryId.ToString(), (int?)_languageId, true,
          Utils.RelativeWebRoot + "Images/PostImages/", numberOfNews, postData.DateCreated);

      DataTable table = moreNewsData.Tables[0];

      int i = 0;
      foreach (DataRow moreNewsDataItem in table.Rows)
      {
        HtmlGenericControl divMoreNews = new HtmlGenericControl("div");
        divMoreNews.Attributes.Add("class", "item-news");
        
        HtmlAnchor anchorMoreNews = new HtmlAnchor();
        anchorMoreNews.Attributes.Add("class", "more-news");
        anchorMoreNews.InnerText = (string)moreNewsDataItem["Title"];
        anchorMoreNews.HRef = "~/Post.aspx?id=" + (Guid)moreNewsDataItem["PostID"];

        divMoreNews.Controls.Add(anchorMoreNews);

        divMoreNewsItems.Controls.Add(divMoreNews);
        
        i++;

        if (i == numberOfNews)
          break;
      }
    }

    private void PreparePrintAnchor(string postId)
    {
      anchorPrintPreview.HRef = "javascript:poptastic('" +
        Utils.AbsoluteWebRoot + "PostPrintPreview.aspx?id=" + 
        postId + "')";

      anchorPrint.HRef = "javascript:poptastic('" +
        Utils.AbsoluteWebRoot + "PostPrintPreview.aspx?id=" +
        postId + "&print=1')";
    }
  }
}
